package com.bluesmart.mia;

import java.util.Calendar;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.db.chart.model.LineSet;
import com.db.chart.model.Point;
import com.db.chart.view.LineChartView;
import com.db.chart.view.AxisController.LabelPosition;
import com.sys.DemoApp;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;
import com.util.Constant;
import com.util.DensityUtil;
import com.util.ImageLoaderHelper;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.util.Utils;
import com.widget.CircleImageView;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class ReportActivity extends BaseActivity implements OnClickListener{
	
	boolean mTab0,mTab1,mTab2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_report);

		((TextView) findViewById(R.id.center)).setText(getString(R.string.report));
		((Button) findViewById(R.id.right)).setCompoundDrawablesWithIntrinsicBounds(0, 0,
				R.drawable.a26, 0);
		
		JSONObject obj = ((DemoApp)getApplicationContext()).getSeletedBaby();

		ImageLoaderHelper.displayImage(R.drawable.a53, (CircleImageView)findViewById(R.id.icon_center), 
				obj.getString("image"));
		
		Date bd = Utils.ConverToDate(obj.getString("bday"), "yyyy-MM-dd");
		long offset = System.currentTimeMillis() - bd.getTime();
		int day = (int)(offset/(24*3600*1000));
		day = day/7;
		
		((TextView)findViewById(R.id.text0)).setText(obj.getString("babyname"));
		((TextView)findViewById(R.id.text2)).setText(day + getString(R.string.week_age));
		
		double weight = obj.getDoubleValue("weight");
		double height = obj.getDoubleValue("height");
		if(((DemoApp) getApplicationContext()).glbUnit == 1)
		{
			weight = 2.2*weight;
			height = height*0.39;

			((TextView)findViewById(R.id.text3)).setText(String.format("%.1f", weight) + "lb");
			((TextView)findViewById(R.id.text1)).setText(String.format("%.1f", height) + "inch");
		}
		else
		{
			((TextView)findViewById(R.id.text3)).setText(String.format("%.1f", weight) + "kg");
			((TextView)findViewById(R.id.text1)).setText(String.format("%.1f", height) + "cm");
		}
		
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.layout0).setOnClickListener(this);
		findViewById(R.id.layout1).setOnClickListener(this);
		findViewById(R.id.layout2).setOnClickListener(this);

		findViewById(R.id.btn0).setOnClickListener(this);
		findViewById(R.id.btn1).setOnClickListener(this);
		findViewById(R.id.btn2).setOnClickListener(this);
		findViewById(R.id.btn3).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);
		
		mController = UMServiceFactory.getUMSocialService("com.umeng.share");
		mController.getConfig().closeToast();
		sendChartHttpRequest();
		
		mTab0 = true;
		
		Calendar calendar = Calendar.getInstance();
		int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		calendar.add(Calendar.DAY_OF_YEAR, -week);
		Date end = calendar.getTime();
		calendar.add(Calendar.DAY_OF_YEAR, -6);
		Date start = calendar.getTime();
		
		((TextView)findViewById(R.id.date_tile)).setText(Utils.ConverToString(start, "yyyy/MM/dd")
				+ " - " + Utils.ConverToString(end, "yyyy/MM/dd"));
	}

	
	public void sendChartHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONArray array = JSON.parseArray(response);
				
				LinearLayout layout = (LinearLayout)findViewById(R.id.layout3);
				layout.setVisibility(View.VISIBLE);
				
				float mMax = 0;
				if(array != null && array.size() > 0)
				{
					LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					
					LineSet lineSet = new LineSet();
					
					int count = array.size();
					for(int i = count - 1; i >= 0; i--)
					{
						JSONObject item = array.getJSONObject(i);
						View convertView = mInflater.inflate(R.layout.item_report, null);
						layout.addView(convertView);
						
						((TextView)convertView.findViewById(R.id.text0)).setText(item.getJSONArray("data").getJSONObject(0).getString("date"));
						
						if(((DemoApp) getApplicationContext()).glbUnit == 1) 
						{
							double consumed_ml = item.getJSONArray("data").getJSONObject(0).getDoubleValue("consumed_ml");
							double goal_ml = item.getJSONArray("goalData").getJSONObject(0).getDoubleValue("goal_ml");
							
							consumed_ml = 0.0325*consumed_ml;
							goal_ml = 0.0325*goal_ml;
							
							((TextView)convertView.findViewById(R.id.text1)).setText(String.format("%.2f", consumed_ml) + "oz");
							((TextView)convertView.findViewById(R.id.text2)).setText(String.format("%.2f", goal_ml) + "oz");
						}
						else
						{
							((TextView)convertView.findViewById(R.id.text1)).setText(item.getJSONArray("data").getJSONObject(0).getString("consumed_ml") + "ml");
							((TextView)convertView.findViewById(R.id.text2)).setText(item.getJSONArray("goalData").getJSONObject(0).getString("goal_ml") + "ml");
						}
						
						float tmp =  item.getJSONArray("data").getJSONObject(0).getFloatValue("consumed_ml");
						lineSet.addPoint(new Point("",tmp));
						
						if(tmp > mMax) mMax = tmp;
					}
					
					LineChartView chart1 = (LineChartView) findViewById(R.id.chart1);
					lineSet.setThickness(DensityUtil.dip2px(ReportActivity.this, 2));
					lineSet.setColor(Color.parseColor("#f26a3d"));
					// Style background fill
					lineSet.setFill(Color.TRANSPARENT);
//					lineSet.setFillColor(Color.RED);
					// Style type
					lineSet.setSmooth(true);
			        
					chart1.addData(lineSet);
					chart1.setXAxis(false);
					chart1.setYAxis(false);
					chart1.setYLabels(LabelPosition.NONE);
					chart1.setYLabels(LabelPosition.NONE);
					chart1.setAxisBorderValues(0, (int)mMax + 100, lineSet.size() + 1);
					chart1.show();
				}
			}
		};
		
		Date date = new Date(System.currentTimeMillis());
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		
		int week = ca.get(Calendar.DAY_OF_WEEK);
		int offset = 0;
		if(week == Calendar.MONDAY) offset = 1;
		else if(week == Calendar.TUESDAY) offset = 2;
		else if(week == Calendar.WEDNESDAY) offset = 3;
		else if(week == Calendar.THURSDAY) offset = 4;
		else if(week == Calendar.FRIDAY) offset = 5;
		else if(week == Calendar.SATURDAY) offset = 6;
		else if(week == Calendar.SUNDAY) offset = 7;
		
		ca.add(Calendar.DAY_OF_MONTH, -offset);
		Date date0 = ca.getTime();
		
		ca.add(Calendar.DAY_OF_MONTH, - 6);
		Date date1 = ca.getTime();

		String end = Utils.ConverToString(date0, "yyyy-MM-dd");
		String start = Utils.ConverToString(date1, "yyyy-MM-dd");
		
		JSONObject params = new JSONObject();
		params.put("mia_un", PreferencesUtils.getString(this, "username"));
		params.put("pwd", PreferencesUtils.getString(this, "password"));
		params.put("start_date", start);
		params.put("end_date", end);
		params.put("handType", "week");
		
		MgqRestClient.postBody(Constant.SERVER_URL + "/sw/GetHistoryFeedData.ashx", JSON.toJSONString(params), loginHandler);
	}
	
/*	public Bitmap convertViewToBitmap(View view) {
		WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		int width = view.getWidth();
		int height = view.getHeight();
		 
		Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
		view.draw(new Canvas(b));
		return b;
	}
	*/
	public static Bitmap getBitmapByView(ScrollView scrollView) {
        int h = 0;
        Bitmap bitmap = null;
        // 获取listView实际高度
        for (int i = 0; i < scrollView.getChildCount(); i++) {
            h += scrollView.getChildAt(i).getHeight();
        }
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        
        return bitmap;
	}
	
	UMSocialService mController;
	String appId = "wxf6f5dfb4e7a3f1e8";
	String appSecret = "20aae0f760949e7fb26863df56c7cb15";
	
	@Override
	public void onClick(View arg0) {
		if(arg0.getId() == R.id.left) finish();
		else if(R.id.right == arg0.getId()) 
		{
			if(findViewById(R.id.bottom).getVisibility() == View.VISIBLE)
			{
				findViewById(R.id.bottom).setVisibility(View.GONE);
			}
			else
			{
				findViewById(R.id.bottom).setVisibility(View.VISIBLE);
			}
		}
		else if(R.id.layout0 == arg0.getId())
		{
			mTab0 = !mTab0;
			if(mTab0) {
				findViewById(R.id.layout3).setVisibility(View.VISIBLE);
				((TextView)findViewById(R.id.layout0)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.a82, 0);
			}
			else{
				findViewById(R.id.layout3).setVisibility(View.GONE);
				((TextView)findViewById(R.id.layout0)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.a81, 0);
			}
		}
		if(R.id.layout1 == arg0.getId())
		{
			mTab1 = !mTab1;
			if(mTab1) ((TextView)findViewById(R.id.layout1)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.a77, 0);
			else ((TextView)findViewById(R.id.layout1)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.a76, 0);
		}
		if(R.id.layout2 == arg0.getId())
		{
			mTab2 = !mTab2;
			if(mTab2) ((TextView)findViewById(R.id.layout2)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.a77, 0);
			else ((TextView)findViewById(R.id.layout2)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.a76, 0);
		}

		Bitmap mScreenShot = getBitmapByView((ScrollView)findViewById(R.id.scrollview));
		if(R.id.btn0 == arg0.getId())
		{
			UMWXHandler wxHandler = new UMWXHandler(this,appId,appSecret);
			wxHandler.addToSocialSDK();
			
			WeiXinShareContent weixinContent = new WeiXinShareContent();
			weixinContent.setTitle("Mia");
			weixinContent.setTargetUrl("http://www.xiaotuguai.com/");
			if(mScreenShot != null) weixinContent.setShareImage(new UMImage(this,mScreenShot));
			mController.setShareMedia(weixinContent);
			mController.postShare(this, SHARE_MEDIA.WEIXIN, new SnsPostListener()
			{
				@Override
				public void onComplete(SHARE_MEDIA arg0, int eCode,
						SocializeEntity arg2) {
					
					if (eCode == 200) {
                    } else {
                        String eMsg = "";
                        if (eCode == -101) {
                            eMsg = "没有授权";
                        }
                        ToastUtil.showToastWithAlertPic("分享失败[" + eCode + "] " + eMsg);
                    }
				}

				@Override
				public void onStart() {
					
				}
			});
		}
		else if(R.id.btn1 == arg0.getId())
		{
			UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, "100424468","c7394704798a158208a74ab60104f0ba");
			qqSsoHandler.addToSocialSDK();  
			
			QQShareContent qqShareContent = new QQShareContent();
			qqShareContent.setTitle("Mia");
			qqShareContent.setTargetUrl("http://www.xiaotuguai.com/");
			if(mScreenShot != null) qqShareContent.setShareImage(new UMImage(this,mScreenShot));
			mController.setShareMedia(qqShareContent);
			mController.postShare(this, SHARE_MEDIA.QQ, new SnsPostListener()
			{
				@Override
				public void onComplete(SHARE_MEDIA arg0, int eCode,
						SocializeEntity arg2) {
					
					if (eCode == 200) {
						ToastUtil.showToastWithAlertPic("分享成功");
                    } else {
                        String eMsg = "";
                        if (eCode == -101) {
                            eMsg = "没有授权";
                        }
                        ToastUtil.showToastWithAlertPic("分享失败[" + eCode + "] " + eMsg);
                    }
				}

				@Override
				public void onStart() {
					
				}
			});
		}
		else if(R.id.btn3 == arg0.getId())
		{
			UMWXHandler wxCircleHandler = new UMWXHandler(this,appId,appSecret);
			wxCircleHandler.setToCircle(true);
			wxCircleHandler.addToSocialSDK();
			
			CircleShareContent circleMedia = new CircleShareContent();
			circleMedia.setTitle("Mia");
			circleMedia.setTargetUrl("http://www.xiaotuguai.com/");
			if(mScreenShot != null) circleMedia.setShareImage(new UMImage(this,mScreenShot));
			mController.setShareMedia(circleMedia);
			mController.postShare(this, SHARE_MEDIA.WEIXIN_CIRCLE, new SnsPostListener()
			{
				@Override
				public void onComplete(SHARE_MEDIA arg0, int eCode,
						SocializeEntity arg2) {
					
					if (eCode == 200) {
                    } else {
                        String eMsg = "";
                        if (eCode == -101) {
                            eMsg = "没有授权";
                        }
                        ToastUtil.showToastWithAlertPic("分享失败[" + eCode + "] " + eMsg);
                    }
				}

				@Override
				public void onStart() {
					
				}
			});
		}
		else if(R.id.btn2 == arg0.getId())
		{
			mController.getConfig().setSsoHandler(new SinaSsoHandler());
			
			SinaShareContent circleMedia = new SinaShareContent();
			circleMedia.setTitle("Mia");
			circleMedia.setTargetUrl("http://www.xiaotuguai.com/");
			if(mScreenShot != null) circleMedia.setShareImage(new UMImage(this,mScreenShot));
			mController.setShareMedia(circleMedia);
			mController.postShare(this, SHARE_MEDIA.SINA, new SnsPostListener()
			{
				@Override
				public void onComplete(SHARE_MEDIA arg0, int eCode,
						SocializeEntity arg2) {
					
					if (eCode == 200) {
						ToastUtil.showToastWithAlertPic("分享成功");
                    } else {
                        String eMsg = "";
                        if (eCode == -101) {
                            eMsg = "没有授权";
                        }
                        ToastUtil.showToastWithAlertPic("分享失败[" + eCode + "] " + eMsg);
                    }
				}

				@Override
				public void onStart() {
					
				}
			});
		}
	
	}
}
